using BackOffice.Application.Services;
using BackOffice.Application.DTOs;
using Backoffice.Domain.Repositories;
using Backoffice.Domain.Entities.App;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace BackOffice.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PermissionController : ControllerBase
    {
        private readonly IPermissionService _permissionService;
        private readonly IRepository<AppPermission> _permissionRepo;

        public PermissionController(IPermissionService permissionService, IRepository<AppPermission> permissionRepo)
        {
            _permissionService = permissionService;
            _permissionRepo = permissionRepo;
        }

        // 分配权限给角色
        [HttpPost("assign/{roleId}")]
        public async Task<IActionResult> AssignPermission(Guid roleId, [FromBody] Guid permissionId)
        {
            var result = await _permissionService.AssignPermissionToRoleAsync(roleId, permissionId);
            return Ok(result.Data);
        }

        // 移除角色的权限
        [HttpDelete("remove/{roleId}")]
        public async Task<IActionResult> RemovePermission(Guid roleId, [FromBody] Guid permissionId)
        {
            var result = await _permissionService.RemovePermissionFromRoleAsync(roleId, permissionId);

            return Ok(result.Data);
        }

        // 获取角色拥有的权限列表
        [HttpGet("role/{roleId}")]
        public async Task<IActionResult> GetPermissionsByRole(Guid roleId)
        {
            var result = await _permissionService.GetPermissionsByRoleAsync(roleId);
            return Ok(result.Data);
        }

        // 获取角色可访问的菜单树
        [HttpGet("menus/{roleId}")]
        public async Task<IActionResult> GetMenusByRole(Guid roleId)
        {
            var result = await _permissionService.GetMenusByRoleAsync(roleId);
            return Ok(result.Data);
        }

        // 获取所有权限（只读列表）
        [HttpGet("list")]
        public async Task<IActionResult> GetPermissions()
        {
            var permissions = await _permissionRepo.GetAllAsync();
            return Ok(permissions);
        }

        // 创建权限
        [HttpPost("create")]
        public async Task<IActionResult> CreatePermission([FromBody] CreatePermissionDto dto)
        {
            try
            {
                var permission = new AppPermission(dto.Code, dto.Name, dto.Description);
                var result = await _permissionRepo.CreateAsync(permission);
                return Ok(new { success = true, permission = result });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 更新权限
        [HttpPut("update/{id}")]
        public async Task<IActionResult> UpdatePermission(Guid id, [FromBody] UpdatePermissionDto dto)
        {
            try
            {
                var permission = await _permissionRepo.GetByIdAsync(id);
                if (permission == null)
                {
                    return NotFound(new { success = false, message = "权限未找到" });
                }

                // 使用实体类的UpdateInfo方法更新属性
                permission.UpdateInfo(dto.Name, dto.Description);

                await _permissionRepo.UpdateAsync(permission);
                return Ok(new { success = true, permission = permission });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        // 删除权限
        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> DeletePermission(Guid id)
        {
            try
            {
                var permission = await _permissionRepo.GetByIdAsync(id);
                if (permission == null)
                {
                    return NotFound(new { success = false, message = "权限未找到" });
                }

                await _permissionRepo.DeleteAsync(id);
                return Ok(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }
    }
}